//
//  MapViewController.m
//  Travelmemory
//
//  Created by lanou3g on 16/3/29.
//  Copyright © 2016年 ABCD. All rights reserved.
//

#import "MapViewController.h"
#import <MAMapKit/MAMapKit.h>
#import "TraveNoteModel.h"
#import "TraveHeader.h"
#import "MapAnnotationView.h"

#define kScreenW self.view.frame.size.width
#define kScreenH self.view.frame.size.height
@interface MapViewController ()<MAMapViewDelegate, UIGestureRecognizerDelegate>

@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) MAPointAnnotation *myself;
@property (nonatomic, strong) NSMutableArray *annotationArray;// 大头针数组
@property (nonatomic, assign) NSInteger currentPosition;
@property (nonatomic, assign) NSTimeInterval duration;
@property (nonatomic, strong) NSMutableArray *picArray;// 图片数组

@end

@implementation MapViewController

#pragma mark - Helper
//
- (void)viewWillAppear:(BOOL)animated{

    self.tabBarController.tabBar.hidden = YES;
}
//
//- (void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:YES];
//    self.tabBarController.tabBar.hidden = NO;
//}

#pragma mark - 初始化大头针
- (void)initCityData
{
    self.annotationArray = [NSMutableArray array];
    self.picArray = [NSMutableArray array];
    for (int i = 0; i < self.allModelArray.count; i++) {
        TraveNoteModel *model = self.allModelArray[i];
        //NSLog(@"%@ %@", model.lat, model.lng);
        
        if (model.lat != nil) {
            
            MAPointAnnotation *ann = [[MAPointAnnotation alloc] init];
            ann.coordinate = CLLocationCoordinate2DMake([model.lat integerValue], [model.lng integerValue]);
            [self.picArray addObject:model.photo_s];
            [self.annotationArray addObject:ann];
        }
    }
}




- (void)viewDidLoad {
    [super viewDidLoad];
   
    
    [MAMapServices sharedServices].apiKey = APIKey2;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(dismissAction)];
    self.navigationItem.title = [self.allModelArray[0] name];
    self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    self.mapView.delegate = self;
    self.mapView.showsCompass = NO;
    self.mapView.scaleOrigin = CGPointMake(5, 22);
    //self.mapView.zoomLevel = 15;
    [self.view addSubview:self.mapView];
    
    [self initCityData];
    
    [self.mapView addAnnotations:self.annotationArray];
    // 将所有的大头针显示在地图上
    [self.mapView showAnnotations:self.mapView.annotations animated:YES];
    // 将起点显示在地图中心
    self.mapView.centerCoordinate = [(MAPointAnnotation *)self.annotationArray[0] coordinate];
    
    UIButton *button1=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    button1.frame = CGRectMake(kScreenW - 100, kScreenH - 90, 70, 25);
    button1.backgroundColor = [UIColor redColor];
    [button1 setTitle:@"回忆旅程" forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(button1) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button1];
    
}


- (void)dismissAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)backAction {
    [self button2];
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 判断移动的方向
double MACoordinateHeading(CLLocationCoordinate2D from, CLLocationCoordinate2D to)
{
    if (!CLLocationCoordinate2DIsValid(from) || !CLLocationCoordinate2DIsValid(to))
    {
        return 0;
    }
    
    double delta_lat_y = to.latitude - from.latitude;
    double delta_lon_x = to.longitude - from.longitude;
    
    if (fabs(delta_lat_y) < 0.000001)
    {
        return delta_lon_x < 0.0 ? 270.0 : 90.0;
    }
    // 移动轨迹的方向
    /**语法:
     ATAN2（Y坐标,X坐标）
     X坐标 点的 X 坐标。
     Y坐标 点的 Y 坐标。
     结果为正表示从 X 轴逆时针旋转的角度，结果为负表示从 X 轴顺时针旋转的角度。
     ATAN2(a, b) 与 ATAN(a/b)稍有不同，ATAN2(a,b)的取值范围介于 -pi 到 pi 之间（不包括 -pi），
     而ATAN(a/b)的取值范围介于-pi/2到pi/2之间（不包括±pi/2)。
     若要用度表示反正切值，请将结果再乘以 180/3.14159。
     另外要注意的是，函数atan2(y,x)中参数的顺序是倒置的，atan2(y,x)计算的值相当于点(x,y)的角度值。
     */
    // atan2(y,x)所表达的意思是坐标原点为起点，指向(x,y)的射线在坐标平面上与x轴正方向之间的角的角度。
    double heading = atan2(delta_lon_x, delta_lat_y) / M_PI * 180.0;
    
    if (heading < 0.0)
    {
        heading += 360.0;
    }
    
    return heading;
}

- (void)animateToNextCoord:(MAPointAnnotation *)annotation
{
    // 如果是最后一个坐标点, 就设置为当前的坐标点为第一个点(原点)
    if (self.currentPosition == self.annotationArray.count)
    {
        self.currentPosition = 0;
        return;
    }
    
    CLLocationCoordinate2D coord = [(MAPointAnnotation *)self.annotationArray[self.currentPosition] coordinate];
    
    CLLocationCoordinate2D previous = annotation.coordinate;
    // 方向
    CLLocationDirection heading = MACoordinateHeading(previous, coord);
    // 距离
    CLLocationDistance distance = MAMetersBetweenMapPoints(MAMapPointForCoordinate(coord), MAMapPointForCoordinate(previous));
    
    //    NSLog(@"p :%d", self.currentPosition);
    NSLog(@"distance :%f, heading :%f", distance, heading);
    
    __weak MapViewController *weakSelf = self;
    
    [UIView animateWithDuration:10 animations:^{
        // 将移动到下一个的坐标设置为当前的坐标点
        [annotation setCoordinate:coord];
        //self.mapView.centerCoordinate = coord;
        
    } completion:^(BOOL finished) {
        
        [self.mapView selectAnnotation:self.annotationArray[self.currentPosition] animated:YES];
        weakSelf.currentPosition++;
        
        if (finished)
        {   // 循环调用
            [weakSelf animateToNextCoord:annotation];
        }
        
    }];
    
    MAAnnotationView *view = [self.mapView viewForAnnotation:self.myself];
    // 移动动画
    view.transform = CGAffineTransformMakeRotation(heading / 180.0 * M_PI);
}

// 开始按钮
- (void)button1
{
    if (self.myself == nil)
    {
        self.myself = [[MAPointAnnotation alloc] init];
        
        self.myself.title = @"kakaka";
        // 设置起始点
        self.myself.coordinate = [(MAPointAnnotation *)self.annotationArray[0] coordinate];
        
        [self.mapView addAnnotation:self.myself];
    }
    

    [self animateToNextCoord:self.myself];
    
}

// 暂停
- (void)button2
{
    MAAnnotationView *view = [self.mapView viewForAnnotation:self.myself];
    [view.layer removeAllAnimations];
    
}

#pragma mark - MAMapViewDelegate
// 自定义大头针
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if (annotation == self.myself)
    {
        static NSString *pointAnnotationIdentifier = @"myselfAnnotationIdentifier";
        
        MAAnnotationView *poiAnnotationView = (MAAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:pointAnnotationIdentifier];
        if (poiAnnotationView == nil)
        {
            poiAnnotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointAnnotationIdentifier];
        }
        
        poiAnnotationView.image = [UIImage imageNamed:@"aeroplane.png"];
        
        poiAnnotationView.canShowCallout = YES;
        
        return poiAnnotationView;
    }
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointAnnotationIdentifier = @"pointAnnotationIdentifier";
        
        //MAPinAnnotationView *poiAnnotationView = (MAPinAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:pointAnnotationIdentifier];
        MapAnnotationView *mapAnnotationView = (MapAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:pointAnnotationIdentifier];
        if (mapAnnotationView == nil)
        {
            mapAnnotationView = [[MapAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointAnnotationIdentifier];
        }
        mapAnnotationView.picArray = self.picArray;
        mapAnnotationView.image = [UIImage imageNamed:@"dest_menu_icon_attration"];
        // 设置为NO，用以调用自定义的calloutView
        mapAnnotationView.canShowCallout = NO;
        // 设置中心点偏移，使得标注底部中间点成为经纬度对应点
        mapAnnotationView.centerOffset = CGPointMake(0, -18);
        mapAnnotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        
        return mapAnnotationView;
    }
    
    return nil;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
